package com.sqx.modules.dataCenter;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sqx.common.utils.Result;
import com.sqx.modules.app.annotation.Login;

import com.sqx.modules.app.dao.TbFootprintDao;
import com.sqx.modules.app.dao.UserDao;
import com.sqx.modules.app.entity.TbFootprint;
import com.sqx.modules.app.entity.UserEntity;
import com.sqx.modules.goods.dao.GoodsDao;
import com.sqx.modules.goods.entity.Goods;
import com.sqx.modules.scFollow.dao.ScFollowDao;
import com.sqx.modules.scFollow.entity.ScFollow;
import com.sqx.modules.scFollow.service.ScFollowService;
import com.sqx.modules.tbCoupon.entity.TbCouponUser;
import com.sqx.modules.tbCoupon.service.TbCouponUserService;
import com.sqx.modules.tbOrders.dao.TbOrdersDao;
import com.sqx.modules.tbOrders.entity.TbOrders;
import com.sqx.modules.trends.dao.TrendsDao;
import com.sqx.modules.trends.entity.Trends;
import com.sqx.modules.trends.service.ITrendsService;
import com.sqx.modules.userCertification.entity.UserCertification;
import com.sqx.modules.userCertification.service.UserCertificationService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("/app/dataCenter/")
@Api(value = "数据中心-用户端", tags = {"数据中心-用户端"})
public class DataCenter {


    @Autowired
    private UserCertificationService certificationService;
    @Autowired
    private ScFollowService followService;

    @Autowired
    private TbCouponUserService couponUserService;
    @Autowired
    private TbFootprintDao footprintDao;

    @Autowired
    private ITrendsService trendsService;

    @Autowired
    private GoodsDao goodsDao;

    @Autowired
    private UserDao userDao;

    @Autowired
    private TbOrdersDao ordersDao;

    @Autowired
    private TrendsDao trendsDao;

    @Autowired
    private ScFollowDao scFollowDao;


    @GetMapping("/getWaitExamine")
    @ApiOperation("获取待审核的数据")
    public Result getWaitExamine() {
        HashMap<String, Object> hashMap = new HashMap<>();
        int userCount = certificationService.count(new QueryWrapper<UserCertification>().eq("status", 0));
        hashMap.put("userCount", userCount);
        return Result.success().put("data", hashMap);
    }

    @Login
    @GetMapping("/getDataInfo")
    @ApiOperation("获取我的页面统计数据")
    public Result getDataInfo(@ApiParam("用户id")@RequestAttribute Long userId) {
        HashMap<String, Object> hashMap = new HashMap<>();
        int followCount = followService.getMyFollowCount(userId);
        int fansCount = followService.count(new QueryWrapper<ScFollow>()
                .eq("by_id", userId)
                .eq("classify", 3));
        // 所有收藏的数量
        int totalCount = 0;
        // 收藏的商品数量
        int followGoodsCount = followService.getMyFollowGoodsCount(userId);
        // 收藏的动态数量
        int followTrendsCount = scFollowDao.selectCountByClassify4(userId);
        // 我想要的数量
        int wantCount = scFollowDao.selectByWantCount(userId);
        totalCount = followGoodsCount + followTrendsCount + wantCount;
        UserEntity goldCount = userDao.selectOne(new QueryWrapper<UserEntity>().eq("user_id", userId));
        int couponCount = couponUserService.count(new QueryWrapper<TbCouponUser>().eq("user_id", userId).eq("status", 0));
        int footprintCount = footprintDao.selectCountByGoodId(userId);
        int trendsCount = trendsDao.selectCountByUserId(userId);
        int releaseCount = goodsDao.selectCount(new QueryWrapper<Goods>().eq("user_id", userId)
                .eq("status", 1)
                .eq("is_enable", 1)
                .eq("good_status",0));
        int sellCount = ordersDao.selectCount(new QueryWrapper<TbOrders>()
                .eq("seller_id", userId)
                .in("status", 1,2,3,4));
        int buyCount = ordersDao.selectCount(new QueryWrapper<TbOrders>()
                .eq("buyer_id", userId)
                .in("status", 1,2,3,4));
        int recycleCount = ordersDao.selectCount(new QueryWrapper<TbOrders>()
                .in("status", 6,7,8)
                .eq("seller_id", userId)
                .eq("retrieve_type", 0));
        Integer creditScore = userDao.selectOne(new QueryWrapper<UserEntity>().eq("user_id", userId)).getCreditScore();
        // 计算信用分百分位
        double creditScorePercentile = calculateCreditScorePercentile(userId);
        BigDecimal amount = new BigDecimal(creditScorePercentile).setScale(2, RoundingMode.HALF_UP);
        // 我的关注数量
        hashMap.put("followCount", followCount);
        // 我的粉丝数量
        hashMap.put("fansCount", fansCount);
        // 金币数量
        hashMap.put("goldCount", goldCount.getTotalGold());
        // 收藏数量
        hashMap.put("followGoodsCount", totalCount);
        // 我的足迹数量
        hashMap.put("footprintCount", footprintCount);
        // 优惠券数量
        hashMap.put("couponCount", couponCount);
        // 动态数量
        hashMap.put("trendsCount", trendsCount);
        // 发布数量
        hashMap.put("releaseCount", releaseCount);
        // 卖出数量
        hashMap.put("sellCount", sellCount);
        // 购买数量
        hashMap.put("buyCount", buyCount);
        // 回收订单数量
        hashMap.put("recycleCount", recycleCount);
        // 信用分
        hashMap.put("creditScore", creditScore);
        // 信用分百分位
        hashMap.put("creditScorePercentile", amount+"%");
        return Result.success().put("data", hashMap);
    }

    // 计算信用分百分位
    private double calculateCreditScorePercentile(Long userId) {
        List<UserEntity> userEntities  =  userDao.selectList(new QueryWrapper<UserEntity>().orderByDesc("credit_score"));
        int rank = 1;
        for (UserEntity userEntity : userEntities) {
            if (userEntity.getUserId().equals(userId)) {
                break;
            }
            if (userEntity.getCreditScore() == 0) {
                break;
            }
            rank++;
        }
        int totalUsers = userEntities.size();
        if (totalUsers == 1) {
            return 100;
        }
        return ((double)(totalUsers - rank) /(totalUsers - 1))* 100;
    }
}
